package com.liuzy.crawler.core;

import java.util.Collections;
import java.util.HashSet;
import java.util.Queue;
import java.util.Set;
import java.util.concurrent.ConcurrentLinkedQueue;

/**
 * 字符串队列对象
 *
 * @author liuzy
 * @since 2015年9月19日
 */
public class StringQueue {

	private Set<String> history = Collections.synchronizedSet(new HashSet<String>());

	private Queue<String> queue = new ConcurrentLinkedQueue<String>();

	private int size;
	private int addCount;
	private int getCount;

	public StringQueue(int size) {
		this.size = size;
	}

	public boolean add(String str) {
		if (str != null && !history.contains(str)) {
			synchronized (queue) {
				if (queue.size() <= size) {
					if (queue.offer(str)) {
						addCount++;
						history.add(str);
					}
					return true;
				} else {
					queue.poll();
					queue.offer(str);
				}
			}
		}
		return false;
	}

	public String get() {
		synchronized (queue) {
			if (queue.isEmpty()) {
				return null;
			} else {
				getCount++;
				return queue.poll();
			}
		}
	}

	public void clear() {
		queue.clear();
	}

	public int[] getStatus() {
		int[] status = {addCount, history.size(), getCount, queue.size()};
		return status;
	}

	@Override
	public String toString() {
		return "h:" + history.size() + "\ta:" + addCount + "\tg:" + getCount + "\tq:" + queue.size();
	}

}
